package com.car.car.service.impl;

import com.car.car.converter.OrderMaster2OrderDTOConverter;
import com.car.car.dataobject.OrderDetail;
import com.car.car.dataobject.OrderMaster;
import com.car.car.dataobject.ProductInfo;
import com.car.car.dto.CartDTO;
import com.car.car.dto.OrderDTO;
import com.car.car.enums.OrderStatusEnums;
import com.car.car.enums.PayStatusEnums;
import com.car.car.enums.ResultEnums;
import com.car.car.exception.SellException;
import com.car.car.repository.OrderDetailRepository;
import com.car.car.repository.OrderMasterRepository;
import com.car.car.service.OrderService;
import com.car.car.service.ProductService;
import com.car.car.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {

        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

        String orderId = KeyUtil.genUniqueKey();

        for(OrderDetail orderDetail : orderDTO.getOrderDetailList()){
            ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
            if(productInfo == null){
                throw  new SellException(ResultEnums.PRODUCT_NOT_EXIST);
            }

            //计算总价
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);

            //订单详情
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetailRepository.save(orderDetail);
        }


        //luo di
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnums.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnums.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        //kou ku cun

        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e->
                new CartDTO(e.getProductId(),e.getProductQuantity())
        ).collect(Collectors.toList());

        productService.decreaseStock(cartDTOList);

     return orderDTO;
    }

    @Override
    public OrderDTO findOne(String OrderId) {
        OrderMaster orderMaster = new OrderMaster();
        orderMaster = orderMasterRepository.findOne(OrderId);

        if(orderMaster == null){
            throw  new SellException(ResultEnums.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrOrderId(OrderId);

        if(CollectionUtils.isEmpty(orderDetailList)){
            throw new SellException(ResultEnums.ORDERDETIAL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid,pageable);

        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        OrderMaster orderMaster = new OrderMaster();
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnums.NEW.getCode())){
            throw new SellException(ResultEnums.ORDER_ERROR_STATUS);
        }

        orderDTO.setOrderStatus(OrderStatusEnums.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster result = orderMasterRepository.save(orderMaster);
        if(result == null){
            throw new SellException(ResultEnums.ORDER_UPDATE_FAIL);
        }

        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            throw new SellException(ResultEnums.ORDER_DETAIL_EMPTY);
        }

        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map( e-> new CartDTO(e.getProductId(),e.getProductQuantity())
                ).collect(Collectors.toList());

        productService.increaseStock(cartDTOList);

        if(orderDTO.getPayStatus().equals(PayStatusEnums.SUCCESS.getCode())){
            //TODO
        }

        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        if(!orderDTO.getOrderStatus().equals(OrderStatusEnums.NEW.getCode())){
            throw new SellException(ResultEnums.ORDER_ERROR_STATUS);
        }

        orderDTO.setOrderStatus(OrderStatusEnums.FINISH.getCode());

        OrderMaster orderMaster = new OrderMaster();

        BeanUtils.copyProperties(orderDTO,orderMaster);

        OrderMaster updateRes = orderMasterRepository.save(orderMaster);

        if(updateRes == null){
            throw new SellException(ResultEnums.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {

        if(!orderDTO.getOrderStatus().equals(OrderStatusEnums.NEW.getCode())){
            throw new SellException(ResultEnums.ORDER_ERROR_STATUS);
        }

        if(!orderDTO.getPayStatus().equals(PayStatusEnums.WAIT.getCode())){
            throw new SellException(ResultEnums.ERROR_PAY_STATUS);
        }

        orderDTO.setPayStatus(PayStatusEnums.SUCCESS.getCode());

        OrderMaster orderMaster = new OrderMaster();

        BeanUtils.copyProperties(orderDTO,orderMaster);

        OrderMaster updateRes = orderMasterRepository.save(orderMaster);

        if(updateRes == null){
            throw new SellException(ResultEnums.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }
}
